package com.atguigu.xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.util.List;

/**
 * Date:2021/3/8
 * Author:ybc
 * Description:
 */
public class ReadXMLTest {

    @Test
    public void testReadMoreElement() throws DocumentException {
        //创建dom4j提供的读取xml文件的对象SAXReader
        SAXReader saxReader = new SAXReader();
        //读取xml
        Document document = saxReader.read("user.xml");
        //获取xml的根标签
        Element rootElement = document.getRootElement();
        //获取userInfo标签
        List userInfoList = rootElement.elements("userInfo");
        //遍历userInfoList
        for (Object o : userInfoList) {
            Element userInfoElement = (Element) o;
            //获取userInfo标签中的子标签
            Element idElement = userInfoElement.element("id");
            Element usernameElement = userInfoElement.element("username");
            Element passwordElement = userInfoElement.element("password");
            Element ageElement = userInfoElement.element("age");
            //获取标签中的文本内容
            System.out.println("id:"+idElement.getText()+",username:"+usernameElement.getText()+",password:"+passwordElement.getText()+",age:"+ageElement.getText());
        }
    }

    @Test
    public void testReadXML() throws DocumentException {
        //创建dom4j提供的读取xml文件的对象SAXReader
        SAXReader saxReader = new SAXReader();
        //读取xml
        Document document = saxReader.read("user.xml");
        //获取xml的根标签
        Element rootElement = document.getRootElement();
        //获取根标签中的子标签
        Element idElement = rootElement.element("id");
        Element usernameElement = rootElement.element("username");
        Element passwordElement = rootElement.element("password");
        Element ageElement = rootElement.element("age");
        //获取标签中的文本内容
        System.out.println("id:"+idElement.getText()+",username:"+usernameElement.getText()+",password:"+passwordElement.getText()+",age:"+ageElement.getText());
    }

}
